/**
  ******************************************************************************
  * @file    mg_test_ble_master.c
  * @author  
  * @version V1.1
  ******************************************************************************
  * @attention
  *
  * <h2><center>&copy; COPYRIGHT 2020 Shanghai Macrogiga Electronics</center></h2>
  *
  ******************************************************************************
  */
#include "mg_driver.h"
#include "mg_ble_control.h"
#include "mg_ble_control_master.h"




extern void led_io_init(void);

void MgBle_Master_Scan(void)
{
    MASTER_SCAN_CFG cfg;
    
    cfg.scan_interval = 160*3; //100ms = 160*0.625
    cfg.scan_window   = 160*3; //100ms = 160*0.625
    cfg.scan_type = SCAN_TYPE_PASSIVE;
    cfg.txAddrType = ADDR_TYPE_RANDOM;
    
    MgBle_CentralScan_Init(&cfg);
    
    while(MgBle_GetCentralScanRunContinueFlag())
    {
        SysGotoStopMode();
    }
    
}

u8 target_ble_addr[7] = {0,0,0,0,0,0,1};
u8 target_ble_found_flag = 0;//rescan if any

////// !!! porting function, this will be invoked by ble lib. !!!/////
void master_connect_app_cfg(void)
{
    MASTER_CONNECT_CFG cfg;
    
    cfg.targetAddrType = 0;
    cfg.txAddrType = ADDR_TYPE_RANDOM;
    cfg.attempt_num = 0xff;//0xff means always try, otherwise one may check the callback of msg[CENTRAL_CONNECT_ATTEMPT_FAILED]
    cfg.connect_interval = 24; /*unit 1.25ms*/
    
    if(!target_ble_found_flag)return;

    cfg.targetAddr[0] = target_ble_addr[0];   //4F 26 00 04 69 ED
    cfg.targetAddr[1] = target_ble_addr[1];
    cfg.targetAddr[2] = target_ble_addr[2];
    cfg.targetAddr[3] = target_ble_addr[3];
    cfg.targetAddr[4] = target_ble_addr[4];
    cfg.targetAddr[5] = target_ble_addr[5];
    cfg.targetAddrType = target_ble_addr[6]; //RxAdd type
    
    MgBle_CentralConnect_Init(&cfg);
}

void MgBle_Master_Connect(void)
{
    //================ BLE master connect init =============
    master_connect_app_cfg();

    //================ BLE Master stack running ============
    while(target_ble_found_flag)
    {
        //*** user task inserted here ***
        //to do...
        
        SysGotoStopMode(); //MCU goto power saving mode
    }
    
    //can ONLY be here if 0 == target_ble_found_flag
}

void test_ble_stack_master(void)
{
    u8 *ble_addr;
    
    led_io_init(); //debug purpose ONLY
    
    UART_Set_baudrate(115200);

    //================== BLE Base band init ================
    MgBle_Init(TXPWR_0DBM, &ble_addr);

    //============ clear MCU pending irq if any ============
    NVIC_IrqClearPendingIRQ(BBSeg_IRQn);
    NVIC_IrqClearPendingIRQ(BB_IRQn);
    
    //============== Enable NVIC IRQ bits ==================
    NVIC_EnableIRQ(INT_MASK_BIT_BB_SEG);
    NVIC_EnableIRQ(INT_MASK_BIT_BB);
    
    while(1)
    {
        MgBle_Master_Scan();
        MgBle_Master_Connect();
    }
}
